package com.inheritance.controller;

import com.inheritance.common.Result;
import com.inheritance.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")  // 添加基础路径
public class UploadController {
    @PostMapping
    public Result<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 1. 判空处理
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        // 获取文件后缀
        String suffix;
        if (file.getOriginalFilename() != null) {
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            try {
                // 4. 生成文件名
                String fileName = UUID.randomUUID() + suffix;
                // 5. 上传文件
                String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
                return Result.success("上传成功", url);
            } catch (IOException e) {
                return Result.error("文件上传失败：" + e.getMessage());
            }
        }
       return Result.success("上传成功");
    }
}
